﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TeamCommunitySolution.Models;
using TeamCommunitySolution.Extensions.ModuleProxies;

namespace TeamCommunitySolution.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {

        BaseModuleProxy baseProxy = new BaseModuleProxy();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(RegistrationModel model)
        {
            try
            {
                if (!String.IsNullOrEmpty(this.baseProxy.FindUserByUsername(model.EMail).NickName))
                {
                    return Content("This email address is already registered. Please follow the procedure to retrieve your password if you have forgotten it.");
                }

                if (!String.IsNullOrEmpty(this.baseProxy.FindUserByNickName(model.NickName).NickName))
                {
                    return Content("This nickname is already registered. Please follow the procedure to retrieve your password if you have forgotten it.");
                }

                this.baseProxy.RegisterUser(model);
                OperationCompleteModel viewModel = new OperationCompleteModel();
                viewModel.Message = "Registration successfully completed";

                if(Request.IsAjaxRequest())
                {
                    return Content("Successful");
                }

                return View("OperationComplete", viewModel);
            }
            catch (Exception e)
            {
                string dialogMsg = "Error {0}";

                if (Request.IsAjaxRequest())
                {
                    dialogMsg = String.Format(dialogMsg, e.Message);
                    return Content(dialogMsg);
                }

                return View("FatalError", e);
            }
        }
    }
}
